import axios,{type InternalAxiosRequestConfig ,type AxiosResponse,type AxiosError} from 'axios'
import { ElMessage } from 'element-plus'
import { useStatusStore } from '../stores/statusStore'

interface ApiResponse<T = any>{
    code:number
    msg:string
    data:T
}



const axiosPlus = axios.create({
    baseURL:import.meta.env.VITE_API_BASE_URL,
    timeout:12000,
    headers:{} as any
})

interface newAxiosRequestConfig extends InternalAxiosRequestConfig{

}


axiosPlus.interceptors.request.use(
  (config:newAxiosRequestConfig):newAxiosRequestConfig =>{
    const token = useStatusStore().token
    if(token && config.headers){
      config.headers.Authorization=`Bearer ${token}`
    }

    return config
  },
  (error:AxiosError)=>{
    ElMessage.error('请求配置错误：' + (error.message || '未知错误'))
    return Promise.reject(error)
  }
)

axiosPlus.interceptors.response.use(
    (response:AxiosResponse<ApiResponse>):any=>{
        const res=response.data;
          if(res.code!==200){
            switch(res.code){
              case 210:
                ElMessage.error(res.msg);
                break;

              default:
                ElMessage.error(`未定义的错误${res.code}`)
            }
          }
        return res.data
    },
    (error:AxiosError<string>):any=>{
        if(error.response){
          const {status} = error.response;
          const errorMessage=error.response.data;
          
          if(typeof error.response.data ==='string'){

          }
          
          switch(status){
            case 401:
              ElMessage.error(errorMessage || '登录状态过期，请重新登录');
              break;
            case 403:
              ElMessage.error(errorMessage || '没有操作权限');
              break;
            case 404:
              ElMessage.error(errorMessage || '请求的资源不存在');
              break;
            case 500:
              ElMessage.error(errorMessage || '服务器内部错误，请稍后重试');
              break;
            default:
              ElMessage.error(`${status},未知的错误`);
          }

          return Promise.reject(new Error(errorMessage))

        }else{

          return Promise.reject(error);
        }
    }
)

const request = {
    get<T = any>(url: string, params: any = {}, config: Partial<newAxiosRequestConfig> = {}): Promise<T> {
    const requestConfig = {
      ...config,
      requestStartTime: Date.now() 
    } as newAxiosRequestConfig
    return axiosPlus.get(url, { params, ...requestConfig })
  },
  post<T = any>(url: string, data: any = {}, config: Partial<newAxiosRequestConfig> = {}): Promise<T> {
    const requestConfig = {
      ...config,
      requestStartTime: Date.now()
    } as newAxiosRequestConfig
    return axiosPlus.post(url, data, requestConfig)
  },
  put<T = any>(url: string, data: any = {}, config: Partial<newAxiosRequestConfig> = {}): Promise<T> {
    const requestConfig = {
      ...config,
      requestStartTime: Date.now()
    } as newAxiosRequestConfig
    return axiosPlus.put(url, data, requestConfig)
  },
  delete<T = any>(url: string, params: any = {}, config: Partial<newAxiosRequestConfig> = {}): Promise<T> {
    const requestConfig = {
      ...config,
      requestStartTime: Date.now()
    } as newAxiosRequestConfig
    return axiosPlus.delete(url, { params, ...requestConfig })
  }
}

export default request